const Koa = require('koa')
const bodyParser = require('koa-bodyparser')
const cors = require('koa-cors')
const logger = require('koa-logger')
const jwt = require('koa-jwt')
const dotenv = require('dotenv')

const { sequelize } = require('./models')
const authRoutes = require('./routes/auth')
const userRoutes = require('./routes/users')
const roleRoutes = require('./routes/roles')
const permissionRoutes = require('./routes/permissions')
const productRoutes = require('./routes/products')
const customerRoutes = require('./routes/customers')
const orderRoutes = require('./routes/orders')
const inventoryRoutes = require('./routes/inventory')
const aiRoutes = require('./routes/ai')
const deepseekRoutes = require('./routes/deepseek')
const reportRoutes = require('./routes/reports')
const tableConfigRoutes = require('./routes/tableConfig')
const chatRoutes = require('./routes/chat')
const systemRoutes = require('./routes/system')
const dynamicMenuRoutes = require('./routes/dynamicMenu')
const sqlLogRoutes = require('./routes/sqlLog')

// 加载环境变量
dotenv.config({ path: '../.env' })

const app = new Koa()

// 中间件
app.use(logger())
app.use(cors({
  origin: function(ctx) {
    console.log('CORS request from origin:', ctx.header.origin)
    const allowedOrigins = [
      'https://xlcig.com',//允许XLCIG.COM访问
      'http://localhost:5520',
      'http://127.0.0.1:5520',
      'http://192.168.11.117:5520',
      'http://localhost:3000',
      'http://127.0.0.1:3000',
      'http://192.168.11.117:3000'
    ]
    if (!ctx.header.origin) return '*'
    return allowedOrigins.includes(ctx.header.origin) ? ctx.header.origin : false
  },
  credentials: true,
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'HEAD'],
  allowHeaders: ['Content-Type', 'Authorization', 'X-Client', 'X-Version', 'Accept', 'X-Requested-With'],
  exposeHeaders: ['Content-Length', 'Content-Type']
}))
app.use(bodyParser())

// JWT中间件 - 排除登录和注册接口
app.use(jwt({ 
  secret: process.env.JWT_SECRET || 'xSynergyOs_JWT_Secret_Key_2024',
  cookie: 'token',
  // 增加时钟偏移容忍度（5分钟）
  clockTolerance: 300
}).unless({ 
  path: [/^\/api\/auth\/login/, /^\/api\/auth\/register/, /^\/$/, /^\/api\/$/]
}))

// JWT错误处理中间件
app.use(async (ctx, next) => {
  try {
    await next()
  } catch (err) {
    console.log('=== JWT Error Caught ===')
    console.log('Error:', err.message)
    console.log('Status:', err.status)
    console.log('Request path:', ctx.path)
    console.log('Request method:', ctx.method)
    console.log('Authorization header:', ctx.headers.authorization)
    console.log('========================')
    
    if (err.status === 401) {
      ctx.status = 401
      ctx.body = {
        success: false,
        message: '未授权访问：请先登录系统',
        error_code: 'UNAUTHORIZED',
        login_url: '/login',
        path: ctx.path
      }
    } else {
      ctx.status = err.status || 500
      ctx.body = {
        success: false,
        message: err.message,
        code: err.status || 500
      }
    }
    console.error('Error:', err)
  }
})

// 路由
app.use(authRoutes.routes())
app.use(userRoutes.routes())
app.use(roleRoutes.routes())
app.use(permissionRoutes.routes())
app.use(productRoutes.routes())
app.use(customerRoutes.routes())
app.use(orderRoutes.routes())
app.use(inventoryRoutes.routes())
app.use(aiRoutes.routes())
app.use(deepseekRoutes.routes())
app.use(reportRoutes.routes())
app.use(tableConfigRoutes.routes())
app.use(chatRoutes.routes())
app.use(systemRoutes.routes())
app.use(dynamicMenuRoutes.routes())
app.use(sqlLogRoutes.routes())

// 健康检查 - 只响应根路径
app.use(async (ctx, next) => {
  if (ctx.path === '/' || ctx.path === '/api' || ctx.path === '/api/') {
    ctx.body = {
      success: true,
      message: 'X-Synergy ERP API is running',
      timestamp: new Date().toISOString()
    }
  } else {
    await next()
  }
})

const PORT = process.env.PORT || 5420

// 启动服务器
const startServer = async () => {
  try {
    // 数据库连接测试
    await sequelize.authenticate()
    console.log(' Database connection has been established successfully.')
    
    // 同步数据库模型
    if (process.env.AUTO_SYNC === 'true') {
      await sequelize.sync({ force: false })
      console.log(' Database models synchronized.')
    }
    
    app.listen(PORT, () => {
      console.log(` X-Synergy ERP API Server is running on port ${PORT}`)
      console.log(` Environment: ${process.env.NODE_ENV}`)
    })
  } catch (error) {
    console.error(' Unable to start server:', error)
    process.exit(1)
  }
}

startServer()

module.exports = app